<?php

include 'config/db_config.php';
include 'lib/kelola_produk.php';
include 'lib/kelola_gambar.php';
include 'lib/upload.php';

session_start();

if(!isset($_SESSION['USERNAME'])){
	header('location:view/login.php');
}

if(isset($_POST['nama_produk']) && isset($_POST['id_kategori']) && isset($_POST['harga']) && isset($_POST['deskripsi'])){
	
	$nama_produk = htmlspecialchars($_POST['nama_produk'], ENT_QUOTES);
	$harga = htmlspecialchars(str_replace('.', '', $_POST['harga']), ENT_QUOTES);
	$id_kategori= htmlspecialchars($_POST['id_kategori'], ENT_QUOTES);
	$deskripsi = nl2br(htmlspecialchars($_POST['deskripsi'], ENT_QUOTES));
	$id_technopreneur = $_SESSION['ID_TECHNOPRENEUR'];
	$tanggal_masuk_produk = date('Y-m-d');
	
	$upload = new upload();
	$kelola_produk = new kelola_produk();
	$kelola_gambar = new kelola_gambar();
	
	$data  = array(
		'ID_TECHNOPRENEUR' => $id_technopreneur,
		'ID_KATEGORI' => $id_kategori, 
		'NAMA_PRODUK' => $nama_produk, 
		'DESKRIPSI_PRODUK' => $deskripsi, 
		'HARGA' => $harga,
		'TANGGAL_MASUK_PRODUK' => $tanggal_masuk_produk
	);
	
	$id_produk = $kelola_produk->insert_produk($data);	
	
	for($i = 1; $i < 6; $i++){
	
		$gambar = "gambar".$i;
		$deskripsi_gambar = "deskripsi_gambar".$i;
		
		if($_FILES[$gambar] != ""){
		
			$deskripsi = null;
			
			if(isset($_POST[$deskripsi_gambar])){
				$deskripsi = nl2br(htmlspecialchars($_POST[$deskripsi_gambar], ENT_QUOTES));
			}
			
			$gambar = $upload->upload_foto($gambar, $_FILES[$gambar], 'images');
			var_dump($gambar);
			if($gambar['set']){
			
				$data = array(
					'ID_PRODUK' => $id_produk,
					'URL' => $gambar['keterangan'],
					'DESKRIPSI_GAMBAR' => $deskripsi
				);
				//var_dump($data)	;
				$kelola_gambar->insert_gambar($data);
				
			}
		}
	}
	
	header('location:view/home_technopreneur.php');
	
}